<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                           |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: xiangminghu@clcw.com.cn                                        |
// +------------------------------------------------------------------------+
//

namespace AuctionBack\Logic;


use AuctionCore\Common\Util;

class LottoryLogic extends BaseLogic
{
    protected $autoCheckFields = false;

    protected $lottoryModel;

    protected $myLottoryModel;

    protected $lottoryTicketModel;

    protected $lottoryTicketLogic;

    public function _initialize()
    {
        $this->lottoryModel = D('Lottory', 'Model');

        $this->myLottoryModel = D('MyLottory', 'Model');

        $this->lottoryTicketModel = D('LottoryTicket', 'Model');

        $this->lottoryTicketLogic = D('LottoryTicket', 'Logic');
    }

    /**
     * 获取开奖活动列表
     *
     * @param int   $page
     * @param int   $pageSize
     * @param array $params
     *
     * @return array
     */
    public function getLottoryList($page, $pageSize, $params)
    {
        $page = $page < 1 ? 1 : (int)$page;
        $pageSize = $pageSize < 1 ? 10 : (int)$pageSize;
        $map = [];
        /**
         * 搜索条件：1、活动ID 2、名称 3、类型 4、状态 5、开始时间 6、结束时间
         */
        if ($params['lot_id']) {
            $map['l.id'] = ['eq', $params['lot_id']];
        }
        if ($params['lot_name']) {
            $map['l.lottory_name'] = ['LIKE', '%' . $params['lot_name'] . '%'];
        }
        if ($params['lot_type']) {
            $map['l.lottory_type'] = ['eq', $params['lot_type']];
        }
        if ($params['lot_status']) {
            $map['l.lottory_status'] = ['eq', $params['lot_status']];
        }
        if ($params['start_time'] && !$params['end_time']) {
            $where['l.lottory_start_time'] = ['egt', strtotime($params['start_time'] . " 00:00:00")];
            $where['l.lottory_end_time'] = ['egt', strtotime($params['start_time'] . " 00:00:00")];
            $where['_logic'] = "OR";
            $map['_complex'] = $where;
        }
        if ($params['end_time'] && !$params['start_time']) {
            $where['l.lottory_start_time'] = ['elt', strtotime($params['end_time'] . " 23:59:59")];
            $where['l.lottory_end_time'] = ['elt', strtotime($params['end_time'] . " 23:59:59")];
            $where['_logic'] = 'OR';
            $map['_complex'] = $where;
        }
        $where = [];
        if ($params['start_time'] && $params['end_time']) {
            $where['l.lottory_start_time'] = [
                ['egt', strtotime($params['start_time'] . " 00:00:00")],
                ['elt', strtotime($params['end_time'] . " 23:59:59")],
                'AND'
            ];
            $where['l.lottory_end_time'] = [
                ['egt', strtotime($params['start_time'] . " 00:00:00")],
                ['elt', strtotime($params['end_time'] . " 23:59:59")],
                'AND'
            ];
            $where['_logic'] = 'OR';
            $map['_complex'] = $where;
        }
        //查询历史活动列表 - 进行中和正常结束
        if ($params['his_lottory']) {
            $map['l.lottory_status'] = [['eq', 2], ['eq', 3], 'OR'];
        }
        //已开奖
        if ($params['history_lottory']) {
            $map['l.lottory_status'] = ['eq', 3];
            $map['l.lottory_win_num'] = ['gt', 0];
        }
        $cols = "l.id,l.lottory_name,l.lottory_image,l.lottory_type,l.lottory_award,l.lottory_win_num,
                 l.lottory_start_time,l.lottory_end_time,l.lottory_time,l.lottory_status,l.create_time";
        $order = "l.id DESC";
        $total = $this->lottoryModel->alias('l')->where($map)->count();
        $list = $this->lottoryModel->alias("l")->field($cols)
            ->where($map)
            ->order($order)
            ->page($page)
            ->limit($pageSize)
            ->select();
        foreach ($list as $k => $v) {
            $list[$k]['lottory_ticket_nums'] = $this->lottoryTicketLogic->getLottoryTicketNum($v['id']);
        }
        $result = [
            'list'  => $list,
            'total' => $total,
        ];
        return $result;
    }

    /**
     * 创建开奖活动
     *
     * @param array $data
     *
     * @return int
     */
    public function createLottory($data = [])
    {
        if (empty($data) && !is_array($data)) {
            return false;
        }
        return $this->lottoryModel->add($data);
    }

    /**
     * 获得开奖活动详情
     *
     * @param int $id
     *
     * @return bool|mixed
     */
    public function getLottoryDetail($id = 0)
    {
        if ($id < 1) {
            return false;
        }
        return $this->lottoryModel->find($id);
    }

    /**
     * 执行开奖操作
     *
     * @param int   $lotId
     * @param float $sse
     * @param float $szs
     * @param int   $lottoryWinNum
     *
     * @return bool
     */
    public function doRunLottory($lotId, $sse, $szs, $lottoryWinNum)
    {
        if ($lotId < 1) {
            return false;
        }
        $data['id'] = $lotId;
        $data['sse'] = $sse;
        $data['szs'] = $szs;
        $data['lottory_win_num'] = $lottoryWinNum;
        M()->startTrans();
        $res1 = $this->lottoryModel->save($data);

        $ticket['lot_id'] = ['eq', $lotId];
        $ticket['lottory_ticket_num'] = ['eq', $lottoryWinNum];
        $res2 = $this->lottoryTicketModel->where($ticket)->setField('lottory_ticket_status', '1');

        $ticketMap['lot_id'] = ['eq', $lotId];
        $ticketMap['lottory_ticket_num'] = ['neq', $lottoryWinNum];
        $res3 = $this->lottoryTicketModel->where($ticketMap)->setField('lottory_ticket_status', '2');

        $winUid = $this->lottoryTicketModel->where($ticket)->getField('uid');
        $myLottory['lot_id'] = ['eq', $lotId];
        $myLottory['uid'] = ['eq', $winUid];
        $res4 = $this->myLottoryModel->where($myLottory)->setField('lot_status', 1);

        $myLottoryMap['lot_id'] = ['eq', $lotId];
        $myLottoryMap['uid'] = ['neq', $winUid];
        $res5 = $this->myLottoryModel->where($myLottoryMap)->setField('lot_status', 2);
        if ($res1 !== false && $res2 !== false && $res3 !== false &&
            $res4 !== false && $res5 !== false
        ) {
            M()->commit();
            return true;
        } else {
            M()->rollback();
            return false;
        }
    }

    /**
     * 上下线活动操作
     *
     * @param $lotId
     * @param $lotStatus
     *
     * @return bool
     */
    public function updateLottoryStatus($lotId, $lotStatus)
    {
        $condition['id'] = $lotId;
        $data['lottory_status'] = $lotStatus;
        if ($lotStatus == 2) {
            $total = $this->lottoryModel->where($data)->count();
            if ($total > 0) {
                echo Util::auto_jsonp_or_json($_REQUEST, ['code' => 500, 'msg' => '已有活动进行中']);
                exit;
            }
            $now = time();
            $where['lottory_start_time'] = ['lt', $now];
            $where['lottory_end_time'] = ['lt', $now];
            $where['_logic'] = 'OR';
            $map['_complex'] = $where;
            $map['id'] = $lotId;
            $totalNum = $this->lottoryModel->where($map)->count();
            if ($totalNum) {
                echo Util::auto_jsonp_or_json($_REQUEST, ['code' => 500, 'msg' => '活动开始时间已过期']);
                exit;
            }
        }
        return $this->lottoryModel->where($condition)
            ->setField($data);
    }

    /**
     * 更新活动
     *
     * @param array $data
     *
     * @return bool
     */
    public function saveLottory($data = [])
    {
        if (empty($data) && !is_array($data)) {
            return false;
        }
        return $this->lottoryModel->save($data);
    }


    /**
     * 获取当前是否有活动，有则返回活动ID，无则返回0
     */
    public function isLottoryOnline()
    {
        $condition['lottory_status'] = 2;
        $condition['lottory_type'] = 1;
        $condition['lottory_start_time'] = ['elt', date("Y-m-d H:i:s")];
        $condition['lottory_end_time'] = ['egt', date("Y-m-d H:i:s")];
        $lotteryList = $this->lottoryModel->where($condition)->select();
        if (!empty($lotteryList)) {
            return $lotteryList;
        } else {
            $lotId = 0;
        }
        return $lotId;
    }

    /**
     * 发送抽奖券
     *
     * @param $uid
     * @param $inCode
     *
     * @return boolean
     */
    public function sendLotteryTicket($uid, $inCode)
    {
        $lotteryList = $this->isLottoryOnline();

        if (empty($lotteryList)) {
            return false;
        }

        foreach ($lotteryList as $item) {
            $redis = new PhpRedis(0);
            $res = $redis->rPush('reg_lottery_list', json_encode([
                    'uid'         => $uid,
                    'lot_id'      => $item['id'],
                    'invite_code' => $inCode]
            ));
        }
        return $res;
    }
}